package controllers

import (
	"encoding/json"
	"getshop/models"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
)

type ShopController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	dh := c.GetString("dh")
	types := c.GetString("types")
	ck := c.GetString("ck")
	stock, _ := c.GetInt("stock")
	price, _ := c.GetFloat("price")
	person := c.GetString("person")

	shop := models.GetShop{

		Dh:     dh,
		Types:  types,
		Ck:     ck,
		Stock:  stock,
		Price:  price,
		Person: person,
	}
	err := models.DB.Debug().Create(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *ShopController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	pageData := make(map[string]interface{})
	key := "page:" + strconv.Itoa(page)
	val, err := models.RedisDB.Get(key).Result()
	if err != nil {

		query := models.DB.Model(&models.GetShop{})
		var count int64
		query.Count(&count)
		offset := (page - 1) * size

		var listget []models.GetShop
		err = query.Offset(offset).Limit(size).Find(&listget).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			pageData["count"] = count
			pageData["listget"] = listget
			jsonrByte, _ := json.Marshal(&pageData)
			value := string(jsonrByte)
			models.RedisDB.Set(key, value, time.Minute*5)

			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: pageData,
			}
			c.ServeJSON()

		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Info() {
	id, _ := c.GetInt("id")
	var infoget models.GetShop
	err := models.DB.Where("id=?", id).First(&infoget).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "仓库查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "仓库查询成功",
			Data: infoget,
		}
		c.ServeJSON()
	}
}
